package org.yray.io.sentinel.config;

import io.etcd.jetcd.*;
import io.etcd.jetcd.watch.WatchEvent;
import io.etcd.jetcd.watch.WatchResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ExecutionException;

@Configuration
@ConditionalOnProperty(value = "etcd.enable",havingValue = "true")
@Slf4j
public class ConfEtcd {

    @Bean
    public Client init() throws ExecutionException, InterruptedException {
        //Client.builder().endpoints("http://172.168.199.93:2379", "http://etcd1:2379", "http://etcd2:2379").build();
        Client client = Client.builder().endpoints("http://172.168.199.93:2379").build();
        // create client using target which enable using any name resolution mechanism provided
        // by grpc-java (i.e. dns:///foo.bar.com:2379)
        Election election=client.getElectionClient();
        Lock lock=client.getLockClient();

        client.getWatchClient().watch(ByteSequence.from("SERVER".getBytes()), new Watch.Listener() {
            @Override
            public void onNext(WatchResponse watchResponse) {
                log.info("watch,next,Events");
                for(WatchEvent watchEvent:watchResponse.getEvents())
                {
                    KeyValue keyValue=watchEvent.getKeyValue();
                    String key=new String(keyValue.getKey().getBytes());
                    String val=new String(keyValue.getValue().getBytes());

                   log.info("watchEvent[type={},key={},val={},",watchEvent.getEventType().name(), key,val);
                }
            }

            @Override
            public void onError(Throwable throwable) {
                log.info("watch,error");
            }

            @Override
            public void onCompleted() {
                log.info("watch,completed");
            }
        });

        //kvClient.delete(key).get();
        return client;
    }
}
